from flask import Blueprint,request,make_response,jsonify
from flask_restful import Resource,Api
from utils.captcha.captcha import captcha
from utils.Myredis import r
import json
login_blue=Blueprint("login",__name__)
api=Api(login_blue)
# 获取图片验证码
# @login_blue.route("/getImageCode")
# def getImageCode():
class GetImageCode(Resource):
    def get(self):
        # 调用captcha生成图片验证码
        name,text,img=captcha.generate_captcha()
        # 存入redis字符串 key:uuid value:text
        uuid=request.args.get("uuid")
        r.str_setex(uuid,text,300)
        res=make_response(img)
        res.headers["Content-Type"]="image/jpg"
        return res
api.add_resource(GetImageCode,"/getimg")

# 发送短信
class SendSms(Resource):
    def post(self):
        # 获取参数
        data=json.loads(request.data)
        mobile=data["mobile"]
        uuid=data["uuid"]
        imagecode=data["imagecode"]
        if not all([mobile,uuid,imagecode]):
            return jsonify({"code":401,"msg":"参数不完整"})
        # 验证图片验证码
        code=r.get_str(uuid)
        # 通过uuid从redis取出来和传递过来的参数进行对比，全部转为小写
        if code:
            if imagecode.lower()!=code.decode().lower():
                return jsonify({"code":402,"msg":"图片验证码不正确"})
            # 清除redis中的图片验证码
            r.del_key(uuid)
        else:
            return jsonify({"code":403,"msg":"没有获取到验证码"})
        # 一分钟只能发送一次
        v=r.get_str(mobile)
        if v:
            return jsonify({"code":403,"msg":"验证码一分钟只能发送一次"})
        # 如果成功调用写入redis队列
        r.list_push("smsmobile",mobile)
        # 短信接口qps限制每秒请求100
        return jsonify({"code":200,"msg":"ok"})
api.add_resource(SendSms,"/sms")